package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Autowired
    private TeachplanMapper teachplanMapper;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;


    /**
     * 根据课程id查询课程计划树型结构
     *
     * @param courseId
     * @return
     */
    @Override
    public List<TeachplanDto> findTeachPlanTree(Long courseId) {
        return teachplanMapper.selectTreeNodesByCourseId(courseId);
    }

    /**
     * 课程计划修改或者创建
     *
     * @param saveTeachplanDto
     */
    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        //拿到课程id
        Long courseId = saveTeachplanDto.getId();
        //判断是新增还是修改
        if (courseId != null) {
            //进行修改
            Teachplan teachplan = teachplanMapper.selectById(courseId);
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        } else {
            //进行新增
            //取出同父级别的课程计划数量
            int count = getTeachplanCount(saveTeachplanDto.getParentid(), saveTeachplanDto.getCourseId());
            Teachplan teachplan = new Teachplan();
            //设置排序号
            teachplan.setOrderby(count + 1);
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            teachplanMapper.insert(teachplan);
        }
    }

    /**
     * 根据课程计划id删除课程计划
     *
     * @param teachplanId
     */
    @Override
    @Transactional
    public void deleteTeachplan(Long teachplanId) {
        //根据课程id先判断删除是一级节点还是二级节点
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan.getGrade().equals(1)) {
            //一级节点---判断一级节点下是否存在二级节点
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid, teachplan);
            Integer count = teachplanMapper.selectCount(queryWrapper);
            if (count > 0) {
                //一级节点下有子节点，不能删除
                XueChengPlusException.cast("课程计划还有子级信息，无法删除");
            }

            int res = teachplanMapper.deleteById(teachplanId);
            if (res <= 0) {
                XueChengPlusException.cast("删除课程计划失败");
            }

        } else {
            //二级节点---同时需要将关联的信息删除
            teachplanMapper.deleteById(teachplanId);
            //查询相关联的媒资信息
            LambdaQueryWrapper<TeachplanMedia> teachplanMediaLambdaQueryWrapper = new LambdaQueryWrapper<>();
            teachplanMediaLambdaQueryWrapper.eq(TeachplanMedia::getTeachplanId, teachplanId);
            TeachplanMedia teachplanMedia = teachplanMediaMapper.selectOne(teachplanMediaLambdaQueryWrapper);
            if (teachplanMedia == null) {
                //没有相关联的信息，直接结束
                return;
            }
            teachplanMediaMapper.deleteById(teachplanMedia);
        }

    }

    /**
     * 课程排序
     *
     * @param moveType
     * @param teachplanId
     */
    @Override
    @Transactional
    public void moveOrDown(String moveType, Long teachplanId) {
        //先找到当前课程计划
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        Integer orderby = teachplan.getOrderby();
        Integer grade = teachplan.getGrade();
        //先判断是向上移还是向下移
        if (moveType.equals("moveup")) {
            //上移
            if (orderby == 1) {
                XueChengPlusException.cast("该课程计划无法上移");
            }
            //找到当前位置上面一个的课程计划
            int moveOrderby = orderby - 1;
            Teachplan MoveTeachplan = teachplanMapper.selectByCourseIdAndOrderby(moveOrderby, grade, teachplan.getCourseId(), teachplan.getParentid());
            //更新这两个字段的排序
            teachplan.setOrderby(MoveTeachplan.getOrderby());
            MoveTeachplan.setOrderby(orderby);
            teachplanMapper.updateById(teachplan);
            teachplanMapper.updateById(MoveTeachplan);

        } else {
            //下移
            int DownOrder = orderby + 1;
            Teachplan DownTeachplan = teachplanMapper.selectByCourseIdAndOrderby(DownOrder, grade, teachplan.getCourseId(), teachplan.getParentid());
            if (DownTeachplan == null) {
                XueChengPlusException.cast("该课程无法下移");
            }
            //更新字段
            teachplan.setOrderby(DownTeachplan.getOrderby());
            DownTeachplan.setOrderby(orderby);
            teachplanMapper.updateById(teachplan);
            teachplanMapper.updateById(DownTeachplan);

        }
    }

    /**
     * 获取最新的排序号
     *
     * @param parentid
     * @param courseId
     * @return
     */
    private int getTeachplanCount(Long parentid, Long courseId) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId);
        queryWrapper.eq(Teachplan::getParentid, parentid);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }


    /**
     * 绑定媒资
     *
     * @param bindTeachplanMediaDto
     */
    @Override
    @Transactional
    public void associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan == null) {
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if (grade != 2) {
            XueChengPlusException.cast("只允许二级标题绑定媒资视频");
        }
        //课程id
        Long courseId = teachplan.getCourseId();
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId, teachplanId);
        //删除之前绑定的媒资信息
        teachplanMediaMapper.delete(queryWrapper);
        //绑定媒资信息
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);

        //修改课程计划基本信息中的课程类型
        teachplan.setMediaType("001002");
        teachplanMapper.updateById(teachplan);
    }


    @Transactional
    @Override
    public void deleteAssociationMedia(Long teachPlanId, String mediaId) {
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachPlanId).eq(TeachplanMedia::getMediaId,mediaId));
    }
}
